import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { sendMobileCode } from '/@/api/login';

export const useSms = () => {
	const sendSmsTimer = ref<number | undefined>();
	const sendSmsText = ref('发送验证码');
	let sendSmsNum = 60;

	/**
	 * 发送短信
	 * @param smsType 发送的短信类型
	 * @param phone 手机号
	 * @param checkFn
	 * @returns
	 */
	async function sendSms(phone: string, checkFn?: () => Promise<boolean>) {
		if (sendSmsTimer.value) return false;

		if (typeof checkFn === 'function') {
			if (!(await checkFn())) return;
		} else {
			if (!phone) {
				ElMessage.warning('请输入手机号');
				return;
			}
		}

		try {
			const resolve = await sendMobileCode(phone);
			if (!resolve.data) {
				throw new Error(resolve.msg);
			}

			ElMessage.success('发送成功');
			sendSmsTimer.value = setInterval(() => {
				sendSmsNum = sendSmsNum - 1;
				if (sendSmsNum <= 0) {
					clearInterval(sendSmsTimer.value);
					sendSmsNum = 60;
					sendSmsText.value = '发送验证码';
					sendSmsTimer.value = undefined;
					return;
				}
				sendSmsText.value = `${sendSmsNum}后可发送`;
			}, 1000);
		} catch (err: any) {
			ElMessage.warning(err.message || '发送失败');
		}
	}

	return {
		sendSms,
		sendSmsText,
		sendSmsTimer,
	};
};
